#include <iostream>
#include <fstream>
#include "contacts.pb.h"

using namespace std;

void PrintContacts(contacts2::Contacts& contacts)
{
    for(int i=0; i<contacts.contacts_size(); i++)
    {
        cout<< "---------联系人"<<i+1<<"------"<<endl;
        // 获取一个联系人信息
        const contacts2::PeopleInfo& people = contacts.contacts(i);
        cout<< "姓名:"<<people.name()<<endl;
        cout<< "年龄:"<<people.age()<<endl;
        for(int j=0; j<people.phone_size();j++)
        {
            const contacts2::PeopleInfo_Phone& phone = people.phone(j);
            cout<< "联系电话："<<phone.number()
            << " (" << phone.PhoneType_Name(phone.type()) <<")" <<endl;
            // phone.type() 获取的是int值，phone.PhoneType_Name(phone.type())是根据int值转为对应的常量名（string）。
        }
        // 判断any字段的data是否设置，且设置的message类型是Address
        if(people.has_data() && people.data().Is<contacts2::Address>())
        {
            contacts2::Address address;
            people.data().UnpackTo(&address); // 将data转为Address类型给address对象
            if(!address.home_address().empty())
            {
                cout<< "家庭地址: "<< address.home_address()<<endl;
            }
            if(!address.unit_address().empty())
            {
                cout<< "单位地址: "<< address.unit_address() << endl;
            }
        }
        // other_contact_case会返回被设置了的字段的标识符序号
        switch(people.other_contact_case())
        {
            case contacts2::PeopleInfo::OtherContactCase::kQq:
                cout<< "qq: "<<people.qq()<<endl;
                break;
            case contacts2::PeopleInfo::OtherContactCase::kWechat:
                cout<< "wechat："<< people.wechat()<<endl;
                break;
            default:
                break;
        }

        if(people.remark_size())
        {
            cout<< "备注："<<endl;
            
        }
        for(auto it = people.remark().cbegin(); it != people.remark().cend(); it++)
        {
            cout<< "  "<<it->first <<" : "<<it->second<<endl;
        }
    }
}

int main()
{
    contacts2::Contacts contacts;
    // 读取已存在的通讯录文件
    fstream input("contacts.bin", ios::in | ios::binary);
    if(!contacts.ParseFromIstream(&input))
    {
        cerr<< "parse error!"<<endl;
        input.close();
        return -1;
    }
    // 打印通讯录列表
    PrintContacts(contacts);
    return 0;
}